<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form'
import type { VxeGridListeners, VxeGridProps } from '#/adapter/vxe-table'

import { h, ref } from 'vue'

import { useDebounceFn } from '@vueuse/core'
import { Modal, Spin } from 'ant-design-vue'

import { useVbenVxeGrid } from '#/adapter/vxe-table'
import { getWareHouse } from '#/api/goodsPurchase'
import { getSupplyList } from '#/api/purchase'
import { getMaterial } from '#/api/spuBom'

const emit = defineEmits(['share-data'])
const data = ref()
const fetching = ref(false)
const keyword = ref('')
const keyword5 = ref('')
const isModalVisible = ref(false)

/**
 * 获取供应商
 */
async function fetchsup({ keyword = '' }: Record<string, any>) {
  const { list } = await getSupplyList({
    quick_search: keyword,
    page: 1,
    limit: 999,
    initKey: 'template_id',
    initValue: undefined,
    select: true,
  })
  return list.map((item: any) => ({
    label: item.SupplyNa,
    value: item.id,
  }))
}

/**
 * 获取仓库
 */
async function fetgetWareHouse({ keyword = '' }: Record<string, any>) {
  const { list } = await getWareHouse({
    quick_search: keyword,
    page: 1,
    limit: 999,
    initKey: 'id',
    initValue: undefined,
    select: true,
  })
  return list.map((item: any) => ({
    label: item.WarehouseName,
    value: item.id,
  }))
}

interface RowType {
  address: string
  age: number
  id: number
  name: string
  nickname: string
  role: string
}

const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: true,
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: '模糊查询',
      },
      fieldName: 'material*material_name',
      label: '面料名称',
      operator: 'LIKE',
    },
    {
      component: 'ApiSelect',
      componentProps: () => {
        return {
          api: fetchsup,
          mode: 'multiple',
          // 禁止本地过滤
          filterOption: false,
          notFoundContent: fetching.value ? undefined : null,
          // 搜索词变化时记录下来， 使用useDebounceFn防抖。
          onSearch: useDebounceFn((value: string) => {
            keyword5.value = value
          }, 300),
          // 远程搜索参数。当搜索词变化时，params也会更新
          params: {
            keyword: keyword5.value || undefined,
          },

          showSearch: true,
          allowClear: true,
        }
      },
      fieldName: 'supply*id',
      label: '档案参考供应商',
      render: 'customRender',
      operator: 'IN',
      renderComponentContent: () => {
        return {
          notFoundContent: fetching.value ? h(Spin) : undefined,
        }
      },
    },
    {
      component: 'ApiSelect',
      componentProps: () => {
        return {
          api: fetgetWareHouse,
          // 禁止本地过滤
          filterOption: false,
          notFoundContent: fetching.value ? undefined : null,
          // 搜索词变化时记录下来， 使用useDebounceFn防抖。
          onSearch: useDebounceFn((value: string) => {
            keyword.value = value
          }, 300),
          // 远程搜索参数。当搜索词变化时，params也会更新
          params: {
            keyword: keyword.value || undefined,
          },
          showSearch: true,
          allowClear: true,
        }
      },
      fieldName: 'warehouse_id',
      operator: '123',
      label: '仓库',
      renderComponentContent: () => {
        return {
          notFoundContent: fetching.value ? h(Spin) : undefined,
        }
      },
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: [
          {
            label: '关闭',
            value: 0,
          },
          {
            label: '开启',
            value: 1,
          },
        ],
        showSearch: true,
      },
      fieldName: 'in_stock',
      operator: '123',
      label: '只看有库存',
    },
  ],
  // 控制表单是否显示折叠按钮
  showCollapseButton: false,
  submitButtonOptions: {
    content: '查询',
  },
  // 是否在字段值改变时提交表单
  submitOnChange: false,
  // 按下回车时是否提交表单
  submitOnEnter: true,
}

const gridOptions: VxeGridProps<RowType> = {
  //   border: true,

  radioConfig: {
    highlight: true,
    labelField: 'name',
    trigger: 'row',
  },
  height: '600px',
  columns: [
    { type: 'radio', width: 70, fixed: 'left' },
    { field: 'material.material_name', title: '面料名称' },
    { field: 'materialColor.name', title: '面料颜色' },
    { field: 'material.price', title: '档案参考单价' },
    { field: 'SupplyNa', title: '档案参考供应商', slots: { default: 'SupplyNa' } },
    { field: 'stock', title: '库存' },
    { field: 'material.unit', title: '单位' },
    { field: 'material.material_attr', title: '成分' },
    { field: 'material.cloth_width', title: '幅宽' },
    { field: 'material.gram_weight', title: '克重' },
  ],
  //   data: [],
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        // return await getRoleList({});
        const search: any[] = await gridApi.formApi.getFiltersValues()
        const res = await getMaterial({
          search,
          page: page.currentPage,
          limit: page.pageSize,
        })

        return {
          items: res.list,
          total: res.total,
        }
      },
    },
  },
  toolbarConfig: {
    // 是否显示搜索表单控制按钮
    // @ts-ignore 正式环境时有完整的类型声明
    search: true,
  },
  pagerConfig: {
    // enabled: false,
  },
}

const gridEvents: VxeGridListeners<RowType> = {
  cellClick: ({ row }) => {
    // message.info(`cell-click: ${row.name}`);
  },
}

const [Grid, gridApi] = useVbenVxeGrid({ formOptions, gridEvents, gridOptions })

// 打开模态框
const openModal = () => {
  isModalVisible.value = true
}

// 关闭模态框
const handleCancel = () => {
  isModalVisible.value = false
}

// 确认选择
const handleOk = () => {
  const checkData = gridApi.grid.getRadioRecord()
  emit('share-data', { ...checkData })
  isModalVisible.value = false
}

// 暴露打开模态框的方法给父组件
defineExpose({
  openModal,
})
</script>
<template>
  <Modal v-model:open="isModalVisible" title="物料列表" width="80%" @ok="handleOk" @cancel="handleCancel" ok-text="确认" cancel-text="取消">
    <Grid class="w-full">
      <template #SupplyNa="{ row }"> {{ row.supply?.SupplyCode }}/{{ row.supply?.SupplyNa }} </template>
    </Grid>
  </Modal>
</template>
